package com.qsl.system.controller;

import com.qsl.common.result.Result;
import com.qsl.common.util.JwtHelper;
import com.qsl.model.system.SysUser;
import com.qsl.model.vo.LoginVo;
import com.qsl.system.exception.BusinessException;
import com.qsl.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * {code: 20000, data: {token: "admin-token"}}
     *
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        // 根据username查询数据
        SysUser sysUsers = sysUserService.getUserInfoByUserName(loginVo.getUsername());
//        判断用户是否存在
        if (sysUsers == null) {
            throw new BusinessException(20001, "用户不存在");
        }
        // 判断密码是否正确
        String password = loginVo.getPassword();
//        String MD5Password = MD5.encrypt(password); // 密码加密后
//        if (!sysUsers.getPassword().equals(MD5Password)) {
//            throw new BusinessException(20001, "密码不正确");
//        }
        // 判断用户状态是否禁用
        if (sysUsers.getStatus() == 0) { // 状态（1：正常 0：停用）
            throw new BusinessException(20001, "用户已禁用");
        }

        // 根据userid和userName生成token字符串，通过map返回
        String token = JwtHelper.createToken(sysUsers.getId(), sysUsers.getName());
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map); // 但返回的状态码(200)和前端(20000)不同
    }


    // {code: 20000, data: {roles: ["admin"], introduction: "I am a super administrator",…}}
    //   avatar:"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"
    //   name:"Super Admin"
    @ApiOperation("获取用户信息（路由数据）")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        // 获取请求头token字符串
        String token = request.getHeader("token");

        // 从token字符串获取用户名称（id）
        String username = JwtHelper.getUsername(token);
        System.out.println("@@@==>" + username);
        // 根据用户名称获取用户信息（基本信息 和菜单权限 和按钮权限数据）
        Map<String, Object> map = sysUserService.getUserinfo(username);
        return Result.ok(map);
    }


    @ApiOperation("退出")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }


}
